package com.example.zyl.common.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.example.zyl.common.CommonResult;
import com.example.zyl.common.exception.LogException;
import com.example.zyl.common.exception.ServiceException;
import com.example.zyl.common.exception.ValidatorException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author zyl
 * &#064;description  全局异常处理
 * @since 2023-11-06
 */
@RestControllerAdvice
public class adviceConfig implements ResponseBodyAdvice<Object> {

    private final Log log = LogFactory.get();

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Object serviceException(ServiceException ex) {
        String message = ex.getMessage();
        log.error("业务异常 ==> {}", message);
        return CommonResult.fail(message);
    }

    @ExceptionHandler(ValidatorException.class)
    @ResponseBody
    public Object validatorException(ValidatorException ex) {
        String message = ex.getMessage();
        log.error("校验参数异常 ==> {}", message);
        return CommonResult.fail(message);
    }

    @ExceptionHandler(LogException.class)
    @ResponseBody
    public Object logException(LogException ex) {
        String message = ex.getMessage();
        log.error("日志异常 ==> {}", message);
        return CommonResult.fail(message);
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return CommonResult.success(o);
    }
}
